package org.sauceggplant.item.man.service.impl;

import org.sauceggplant.item.man.dto.SqlDto;
import org.sauceggplant.item.man.service.DbConnectionService;
import org.sauceggplant.item.man.service.SqlExecuteService;

import java.sql.*;
import java.util.Date;

public class SqlExecuteServiceImpl implements SqlExecuteService {

    private DbConnectionService dbConnectionService;

    public SqlExecuteServiceImpl() {
        dbConnectionService = new DbConnectionServiceImpl();
    }

    @Override
    public int execute(SqlDto sqlDto) throws SQLException {
        PreparedStatement statement = prepareStatement(sqlDto);
        return statement.executeUpdate();
    }

    @Override
    public ResultSet executeQuery(SqlDto sqlDto) throws SQLException {
        PreparedStatement statement = prepareStatement(sqlDto);
        return statement.executeQuery();
    }

    protected PreparedStatement prepareStatement(SqlDto sqlDto) throws SQLException {
        Connection connection = dbConnectionService.getConnection(sqlDto.getType());
        if (null == connection) {
            throw new SQLException(SqlExecuteServiceImpl.class.getName() + ":connection is null");
        }
        PreparedStatement preparedStatement = connection.prepareStatement(sqlDto.getSql());
        if (null == preparedStatement) {
            throw new SQLException(SqlExecuteServiceImpl.class.getName() + ":preparedStatement is null");
        }
        int index = 1;
        for (Object param : sqlDto.getParams()) {
            if (param instanceof String) {
                preparedStatement.setString(index, (String) param);
            }
            if (param instanceof java.util.Date) {
                preparedStatement.setTimestamp(index, new Timestamp(((Date) param).getTime()));
            }
            if (param instanceof Long) {
                preparedStatement.setLong(index, (Long) param);
            }
            if (param instanceof Integer) {
                preparedStatement.setInt(index, (Integer) param);
            }
            ++index;
        }
        return preparedStatement;
    }
}
